package com.lib.framework.widget.dialog

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.view.View
import com.lib.framework.R
import com.lib.framework.utils.FileUtil
import com.lib.framework.widget.WidgetUtil
import com.lib.framework.widget.dialog.bottomlist.BottomListDialog
import com.lib.framework.widget.dialog.bottomlist.BottomListDialogItem
import org.devio.takephoto.app.TakePhotoActivity
import org.devio.takephoto.compress.CompressConfig
import org.devio.takephoto.model.CropOptions
import org.devio.takephoto.model.TResult
import org.devio.takephoto.model.TakePhotoOptions
import java.io.File


/**
 * 获取图片对话框，从相册或者相机获取
 *
 * @author keanbin
 */
class GetImgDialog : TakePhotoActivity() {

    companion object {

        /**
         * 文本
         */
        var sPhotographText =
            WidgetUtil.getStringFromRes(R.string.photograph) // 拍照文本
        var sSelectFromAlbumText =
            WidgetUtil.getStringFromRes(R.string.SelectFromAlbum) // 相册文本
        var sGetImgFailText =
            WidgetUtil.getStringFromRes(R.string.getImgFail) // 获取不到相册

        /**
         * 返回获取的图片列表
         */
        const val INTENT_KEY_IMGS = "imgs"

        /**
         * 是否裁剪
         */
        private const val INTENT_KEY_IS_CROP = "isCrop"

        /**
         * 裁剪的高度
         */
        private const val INTENT_KEY_CROP_HEIGHT = "CropHeight"

        /**
         * 裁剪的宽度
         */
        private const val INTENT_KEY_CROP_WIDTH = "CropWidth"

        /**
         * 取消按钮的文本
         */
        private const val INTENT_KEY_CANCEL_TEXT = "cancelText"

        /**
         * 默认的裁剪高度
         */
        private const val DEFAULT_CROP_HEIGHT = 400

        /**
         * 默认的裁剪宽度
         */
        private const val DEFAULT_CROP_WIDTH = 400

        /**
         * 弹框是否有title
         */
        private const val INTENT_KEY_DIALOG_TITLE = "dialog_title"

        /**
         * 显示获取图片对话框
         */
        fun showGetImgDialog(activity: Activity, requestCode: Int, isCrop: Boolean = true,
                             cropHeight: Int = DEFAULT_CROP_HEIGHT, cropWidth: Int = DEFAULT_CROP_WIDTH,
                             cancelText: String? = null) {
            val intent = Intent(activity, GetImgDialog::class.java)
            intent.putExtra(INTENT_KEY_IS_CROP, isCrop)
            intent.putExtra(INTENT_KEY_CROP_HEIGHT, cropHeight)
            intent.putExtra(INTENT_KEY_CROP_WIDTH, cropWidth)

            if (!cancelText.isNullOrEmpty()) {
                intent.putExtra(INTENT_KEY_CANCEL_TEXT, cancelText)
            }

            activity.startActivityForResult(intent, requestCode)
        }

        fun showGetImgDialog2(activity: Activity, requestCode: Int, isCrop: Boolean = true, title: String? = null,
                              cancelText: String? = null) {
            val intent = Intent(activity, GetImgDialog::class.java)
            intent.putExtra(INTENT_KEY_IS_CROP, isCrop)
            intent.putExtra(
                INTENT_KEY_CROP_HEIGHT,
                DEFAULT_CROP_HEIGHT
            )
            intent.putExtra(
                INTENT_KEY_CROP_WIDTH,
                DEFAULT_CROP_WIDTH
            )
            intent.putExtra(INTENT_KEY_DIALOG_TITLE, title)

            if (!cancelText.isNullOrEmpty()) {
                intent.putExtra(INTENT_KEY_CANCEL_TEXT, cancelText)
            }

            activity.startActivityForResult(intent, requestCode)
        }
    }

    //弹框的title
    private var mDialogTitle: String? = null

    private var mDialog: Dialog? = null

    /**
     * 是否裁剪
     */
    private var mIsCrop = true

    /**
     * 裁剪的高度，也是压缩的高度
     */
    private var mCropHeight =
        DEFAULT_CROP_HEIGHT

    /**
     * 裁剪的宽度，也是压缩的宽度
     */
    private var mCropWidth =
        DEFAULT_CROP_WIDTH

    /**
     * 取消文本
     */
    private var mCancelText: String? = null

    /**
     * 是否跟随对话框消失而关闭页面
     */
    private var mIsFinishByDialogDismiss = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_empty_transparency)

        if (savedInstanceState != null) {
            mIsFinishByDialogDismiss = savedInstanceState.getBoolean("mIsFinishByDialogDismiss", false)
            mIsCrop = savedInstanceState.getBoolean("mIsCrop", true)
            mCropHeight = savedInstanceState.getInt("mCropHeight",
                DEFAULT_CROP_HEIGHT
            )
            mCropWidth = savedInstanceState.getInt("mCropWidth",
                DEFAULT_CROP_WIDTH
            )
            mDialogTitle = savedInstanceState.getString(INTENT_KEY_DIALOG_TITLE, null)
            mCancelText = savedInstanceState.getString(INTENT_KEY_CANCEL_TEXT, null)
        } else {
            mIsCrop = intent.getBooleanExtra(INTENT_KEY_IS_CROP, true)
            mCropHeight = intent.getIntExtra(
                INTENT_KEY_CROP_HEIGHT,
                DEFAULT_CROP_HEIGHT
            )
            mCropWidth = intent.getIntExtra(
                INTENT_KEY_CROP_WIDTH,
                DEFAULT_CROP_WIDTH
            )
            mDialogTitle = intent.getStringExtra(INTENT_KEY_DIALOG_TITLE)
            mCancelText = intent.getStringExtra(INTENT_KEY_CANCEL_TEXT)
            showDialog()
        }
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        outState?.putBoolean("mIsFinishByDialogDismiss", mIsFinishByDialogDismiss)
        outState?.putBoolean("mIsCrop", mIsCrop)
        outState?.putInt("mCropHeight", mCropHeight)
        outState?.putInt("mCropWidth", mCropWidth)
        super.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        super.onDestroy()

        closeDialog()
    }

    /**
     * 获取图片成功
     */
    override fun takeSuccess(result: TResult?) {
        super.takeSuccess(result)

        if (result == null) {
            takeFail(result, sGetImgFailText)
            return
        }

        val intent = Intent()
        intent.putExtra(INTENT_KEY_IMGS, result.images)
        setResult(1, intent)
        finish()
    }

    override fun finish() {
        super.finish()
    }

    /**
     * 获取失败
     */
    override fun takeFail(result: TResult?, msg: String?) {
        super.takeFail(result, msg)

        finish()
    }

    /**
     * 取消获取
     */
    override fun takeCancel() {
        super.takeCancel()

        finish()
    }

    /**
     * 显示对话框
     */
    private fun showDialog() {
        if (mDialog?.isShowing == true) {
            return
        }

        if (mDialog == null) {
            val textList = mutableListOf<BottomListDialogItem>()
            mDialogTitle?.let {
                textList.add(BottomListDialogItem(1 ,it, flag = BottomListDialogItem.FLAG_TITLE))
            }
            textList.add(BottomListDialogItem(2, sPhotographText))
            textList.add(BottomListDialogItem(3, sSelectFromAlbumText))
            val dialog = BottomListDialog(this, textList)
            dialog.setOnItemClickListener(object : BottomListDialog.OnItemClickListener {
                override fun onItemClick(view: View, id: Int, position: Int) {
                    when (id) {
                        2 -> { // 拍照
                            mIsFinishByDialogDismiss = false
                            getImgFromCamera()
                            closeDialog()
                        }

                        3 -> { // 从相册选择
                            mIsFinishByDialogDismiss = false
                            getImgFromGallery()
                            closeDialog()
                        }
                    }
                }
            })

            mCancelText?.let {
                dialog.setCancelText(it)
            }
            dialog.setCancelOnClickListener(View.OnClickListener {
                closeDialog()
            })

            dialog.setOnDismissListener {
                if (mIsFinishByDialogDismiss) {
                    finish()
                }
            }

            mDialog = dialog
        }

        mDialog?.show()
    }

    /**
     * 关闭对话框
     */
    private fun closeDialog() {
        mDialog?.cancel()
        mDialog = null
    }

    /**
     * 获取图片uri
     */
    private fun getImgUri(): Uri {
        val file = File(Environment.getExternalStorageDirectory(), FileUtil.TMP_PATH + System.currentTimeMillis() + ".jpg")
        if (!file.parentFile.exists()) {
            file.parentFile.mkdirs()
        }

        return Uri.fromFile(file)
    }

    /**
     * 从相册获取图片
     */
    private fun getImgFromGallery() {
        setCompress()
//        val limit = 4 // 多选，但是现在会崩溃
        if (!mIsCrop) {
            takePhoto.onPickFromGallery()
//            takePhoto.onPickMultiple(limit) // 多选，但是现在会崩溃
            return
        }

        takePhoto.onPickFromGalleryWithCrop(getImgUri(), getCropOptions())
//        takePhoto.onPickMultipleWithCrop(limit, getCropOptions()) // 多选，但是现在会崩溃
    }

    /**
     * 从相机获取图片
     */
    private fun getImgFromCamera() {
        setCompress()
        if (!mIsCrop) {
            takePhoto.onPickFromCapture(getImgUri())
            return
        }

        takePhoto.setTakePhotoOptions(TakePhotoOptions.Builder().setCorrectImage(true).setWithOwnGallery(true).create())
        takePhoto.onPickFromCaptureWithCrop(getImgUri(), getCropOptions())
    }

    /**
     * 获取裁剪配置
     */
    private fun getCropOptions(): CropOptions? {
        if (!mIsCrop) {
            return null
        }
        val height = mCropHeight
        val width = mCropWidth
        val withWonCrop = false

        val builder = CropOptions.Builder()
//        builder.setOutputX(width).setOutputY(height)
        builder.setAspectX(width).setAspectY(height)
        builder.setOutputX(width).setOutputY(height)
        builder.setWithOwnCrop(withWonCrop)
        return builder.create()
    }

    /**
     * 设置压缩
     */
    private fun setCompress() {
        // 鲁班会改变宽度和高度
//        val option = LubanOptions.Builder()
//            .setMaxHeight(mCropHeight)
//            .setMaxWidth(mCropWidth)
//            .setMaxSize(100 * 1024) // 单位B
//            .create()
//        val config = CompressConfig.ofLuban(option)
//        config.enableReserveRaw(true)
//        takePhoto.onEnableCompress(config, true)

        val config = CompressConfig.Builder().setMaxSize(100 * 1024)
            .setMaxPixel(if (mCropWidth >= mCropHeight) mCropWidth else mCropHeight)
            .enableReserveRaw(true)
            .create()
        takePhoto.onEnableCompress(config, true)
    }
}